package com.xm.gateway.filter;

import com.xm.gateway.config.TraceIdProperties;
import com.xm.gateway.util.TraceIdUtil;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 生成日志链路追踪id，并传入header中
 */
@Component
public class TraceIdFilter implements GlobalFilter, Ordered {
    @Resource
    private TraceIdProperties traceIdProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (traceIdProperties.getEnable()) {
            //链路追踪id
            TraceIdUtil.addTrace();

            ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                    .headers(h -> {
                        h.add(TraceIdUtil.TRACE_ID_HEADER, TraceIdUtil.getTraceId());
                        h.add(TraceIdUtil.SPAN_ID_HEADER, TraceIdUtil.getNextSpanId());
                    })
                    .build();

            ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
            return chain.filter(build);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
